import datetime
import time
from nonebot.adapters.cqhttp import Bot
from nonebot.adapters.cqhttp.event import Event
from nonebot.permission import SUPERUSER

from nonebot.plugin import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State

from ...dao import group_dao, assignment_dao, class_student_dao, submit_record_dao
from ...utils.utils import get_options_list
from ...model.assignment import Assignment


launch_assignment = on_command("发布作业", rule=to_me(), permission=SUPERUSER)


@launch_assignment.handle()
async def launch_assignment_handler(bot: Bot, event: Event, state: T_State):
    cls_list = await group_dao.getAllClass(bot)
    cls_options = get_options_list(list(map(lambda x: x.name, cls_list)))
    state["cls_list"] = cls_list
    state["class_count"] = len(cls_list)
    await launch_assignment.send(cls_options)


@launch_assignment.got("class_no", prompt="你想在哪个班发布作业呢？")
async def handle_class(bot: Bot, event: Event, state: T_State):
    try:
        num = int(state["class_no"])
    except ValueError:
        await launch_assignment.reject("请输入数字！")

    if num < 0 or state["class_count"] <= num:
        await launch_assignment.reject("请输入在{}到{}之间的数字！".format(0, state["class_count"] - 1))

    # get target group_id
    cls_list = state["cls_list"]
    cls_gids = list(map(lambda x: x.gid, cls_list))
    target_gid = cls_gids[num]
    state["target_gid"] = target_gid

    
@launch_assignment.got("day", prompt="几天后截止？")
async def handle_date(bot: Bot, event: Event, state: T_State):
    try:
        days = int(state["day"])
    except ValueError:
        await launch_assignment.reject("请输入数字！")

    if days < 0:
        await launch_assignment.reject("请输入大于零的数字！")
    


@launch_assignment.got("hour", prompt="具体几点钟？(输入小时即可，例如18代表下午6时)")
async def handle_time(bot: Bot, event: Event, state: T_State):
    try:
        hour = int(state["hour"])
    except ValueError:
        await launch_assignment.reject("请输入数字！")

    if hour < 1 or hour > 23:
        await launch_assignment.reject("请输入在1到23之间的数字！")
        
@launch_assignment.got("name", prompt="本次作业名是？")
async def handle_name(bot: Bot, event: Event, state: T_State):
    name = state["name"]
    
    target_gid = state["target_gid"]
    
    # insert the assignment into DB(Assignment)
    data = []
    data.append(None)
    data.append(target_gid)
    data.append(name)
    now = datetime.datetime.now()
    delta_hour = int(state["hour"]) - now.hour
    day = int(state["day"])
    delta = datetime.timedelta(days=day,hours=delta_hour)
    n_days = now + delta 
    data.append(int(round(n_days.timestamp() * 1000)))
    data.append(1)
    attendance = Assignment(data)
    await assignment_dao.insert_assignment(attendance)

    # insert the defalut submit_record into DB(Submit_Record)
    assignmentID = await assignment_dao.get_assignment_id(target_gid, name)
    studentID_list = await class_student_dao.get_class_student_list(target_gid)
    await submit_record_dao.insert_record(assignmentID[0], studentID_list)
    
    await launch_assignment.send("作业发布成功")
